package com.zzyl.common.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

public class SerialNumberGeneratorUtils {
    // 时间格式：yyyyMMddHHmmss
    private static final DateTimeFormatter FORMATTER = 
        DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    
    // 当前时间戳缓存
    private static volatile String currentTimestamp;
    
    // 序号生成器（原子操作保证线程安全）
    private static final AtomicInteger sequence = new AtomicInteger(0);

    public static synchronized String generate() {
        LocalDateTime now = LocalDateTime.now();
        String newTimestamp = now.format(FORMATTER);
        
        // 时间戳变化时重置序号
        if (!newTimestamp.equals(currentTimestamp)) {
            currentTimestamp = newTimestamp;
            sequence.set(0);
        }
        
        // 生成4位序号（0001-9999）
        int seq = sequence.incrementAndGet();
        if (seq > 9999) {
            throw new IllegalStateException("Sequence overflow (max 9999 per second)");
        }
        
        return String.format("%s%04d", currentTimestamp, seq);
    }
}
